Ext.define('UmlWebEditor.controller.WorkSpaceController', {
	extend: 'Ext.app.Controller',
	views: [
		'WorkSpace',
		'ToolsCollection'
	],
	requires: [
		'UmlWebEditor.view.WorkSpace',
		'UmlWebEditor.view.ToolsCollection',
		'UmlWebEditor.view.toolbars.MainToolBar',
		'UmlWebEditor.factories.BlocksFactory'
	],
	onWorkSpaceWidgetRender: function (view) {
		console.log('WorkSpaceController: onWorkSpaceWidgetRender');
		this.getWorkSpaceWidget = function() {
			return view;
		};
		if((view.getDiagrammStore().count() == 0)&&(!view.getDiagrammStore().isLoading()))
			this.onCreateDiagramm('CommonDiagramm');
	},
	onToolBarRender: function (view) {
		console.log('WorkSpaceController: onToolBarRender' + view.self.getName());
		var me = this;
		view.on(view.onCreateDiagramm, function(diagrammType) {
			console.log('WorkSpaceController: onCreateDiagramm');
			me.onCreateDiagramm(diagrammType);
		});						
		this.getMainToolBarWidget = function() {
			return view;
		};
	},
	onCollectionRender: function (view) {
		console.log('WorkSpaceController: onCollectionRender');
	},
	onCreateDiagramm: function (diagrammType) {
		console.log('WorkSpaceController: onCreateDiagramm');
		var widget = this.getWorkSpaceWidget();
		var store = widget.getDiagrammStore();
		factory = Ext.create('UmlWebEditor.factories.BlocksFactory');
		key = factory.getNextId();
		store.add({
			key: key,
			blockKey: -1,
			type: diagrammType,
			name: diagrammType + ' ' + key
		});
	},
	onChooseDiagramm: function (diagramm) {
		console.log('WorkSpaceController: onChooseDiagramm');
		var widget = this.getWorkSpaceWidget();
		widget.chooseDiagramm(diagramm);
		var commonDiagrammController = this.getController('CommonDiagrammController');
		commonDiagrammController.setCurrentDiagramm(diagramm);
	},
	onDiagrammCreated: function (diagramm) {
		console.log('WorkSpaceController: onDiagrammCreated');
		var widget = this.getMainToolBarWidget();
		widget.onDiagrammCreated(diagramm);
	},
	init: function() {
		var me = this;
		console.log('WorkSpaceController: init');
		this.control({
			'WorkSpace': {
				afterrender: function(view) {
					me.onWorkSpaceWidgetRender(view);
				},
				diagrammCreatedEvent: function(diagramm) {
					me.onDiagrammCreated(diagramm);
				}
			},
			'MainToolBar': {
				afterrender: function(view) {
					me.onToolBarRender(view);
				},
				createDiagrammEvent: function(diagrammType) {
					console.log('WorkSpaceController: createDiagrammEvent');
					me.onCreateDiagramm(diagrammType);
				},
				chooseDiagrammEvent: function(diagrammType) {
					console.log('WorkSpaceController: chooseDiagrammEvent');
					me.onChooseDiagramm(diagrammType);
				}
			},
			'ToolsCollection': {
				afterrender: function(view) {
					me.onCollectionRender(view);
				}
			},
		});
	}
});
